package chabernac.android.wordbattle;

import java.util.concurrent.Executors;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import chabernac.android.wordbattle.WordRasterGameMediatorFactory.GameType;

public class WordBattleActivity extends AbstractWordBattleActivity {
  private String myLanguage;
  private int myRows;
  private int myColumns;
  private GameType myGameType;
  private ProgressDialog myProgressDialog = null;

  public WordBattleActivity(){
    super();
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    extractGameProperties();
    showSpinnerUntillLanguageLoaded();
  }

  private void extractGameProperties(){
    Bundle theProperties = getIntent().getExtras();
    myLanguage = theProperties.getString( "language" );
    myRows = theProperties.getInt( "rows" );
    myColumns = theProperties.getInt( "columns" );
    myGameType = GameType.valueOf( theProperties.getString( "gameStyle" ));

  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
      if(myProgressDialog.isShowing()) myProgressDialog.dismiss();
    }
    return super.onKeyDown(keyCode, event);
  }


  private void showSpinnerUntillLanguageLoaded() {
    myProgressDialog = ProgressDialog.show(WordBattleActivity.this, "", getText( R.string.loadLanguage ), true);
    myProgressDialog.setCancelable( true );
    myProgressDialog.show();

    myProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override
      public void onCancel( DialogInterface aDialog ) {
        onBackPressed();
      }
    });


    Executors.newSingleThreadExecutor().execute( new Runnable(){
      public void run(){
        try {
          WordRasterContext.getInstance().getDatabaseLoaderDecorator().waitForLanguage( getSelectedLanguage() );
          //init the game when the language is loaded
          runOnUiThread( new Runnable(){
            public void run(){
              myProgressDialog.setMessage( "Creating Game..." );
            }
          });
          WordRasterGameMediator theMediator = WordRasterGameMediatorFactory.createGame( myGameType, myLanguage, myRows, myColumns );
          WordRasterContext.getInstance().setMediator(theMediator);

          //only when the langauge is loaded set the content
          runOnUiThread( new Runnable(){
            public void run(){
              setContentView(R.layout.wordraster);
            }
          });
        } catch ( InterruptedException e ) {
        }
        runOnUiThread( new Runnable(){
          public void run(){
            myProgressDialog.dismiss();    
          }
        });
      }
    });
  }
}